//
//  SetUpTableViewController.swift
//  serverMonitor
//
//  Created by joke on 15/12/31.
//  Copyright © 2015年 joke. All rights reserved.
//

import UIKit
import CoreData

class SetUpTableViewController: UITableViewController,UICollectionViewDelegate{

    @IBAction func addMonitor(sender: AnyObject) {
        let alert = UIAlertController(title: "添加监视", message: "hello", preferredStyle: .Alert)
        
        
        
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel) { (action:UIAlertAction!) -> Void in
            print("press cancel")
        }
        
        let okAction = UIAlertAction(title: "确定", style: .Default) { (action:UIAlertAction!) -> Void in
            
            let address = alert.textFields![1] as UITextField
            let name = alert.textFields![0] as UITextField
            if ((address.text == nil) || (address.text?.characters.count == 0) || (name.text == nil) || (name.text?.characters.count == 0)){
                print(0)
            }else{
            
            self.saveName(name.text!,address: address.text!)
            
            //使用插入新值的方法来添加新值，可以增加动画
            let indexPath = NSIndexPath(forItem: (self.monitorName.count-1), inSection: 0)
                self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
            }
        }
        
        
        alert.addTextFieldWithConfigurationHandler { (textField:UITextField) -> Void in
            
            textField.placeholder = "输入名称"
            textField.becomeFirstResponder()//使文本框在界面打开时就获取焦点，并弹出输入键盘
            textField.resignFirstResponder()//使文本框失去焦点，并收回键盘
            //textField.keyboardType = UIKeyboardType.DecimalPad //显示用于输入数字和小数点的虚拟键盘
            
            
        }
        
        
        alert.addTextFieldWithConfigurationHandler { (textField:UITextField) -> Void in
            
            textField.placeholder = "输入地址"
            textField.becomeFirstResponder()//使文本框在界面打开时就获取焦点，并弹出输入键盘
            textField.resignFirstResponder()//使文本框失去焦点，并收回键盘
            //textField.keyboardType = UIKeyboardType.DecimalPad //显示用于输入数字和小数点的虚拟键盘
            
            
        }

        
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        
        //防止弹出alert时出现UIAlertControllerCollectionViewFlowLayout问题
        alert.view.setNeedsLayout()
        
        presentViewController(alert, animated: true, completion: nil)
        
        
    }
    
    
    
    var monitorName = [MonitorData]()
    
    func saveName(name:String,address:String){
        
        //1 获取总代理和托管内容总管
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //获取总代理
        let managedContext = appDelegate.managedObjectContext //
        
        //2 建议一个entity
        let entity = NSEntityDescription.entityForName("MonitorData", inManagedObjectContext: managedContext)
        let monitor = MonitorData(entity: entity!, insertIntoManagedObjectContext: managedContext)
        
        monitor.name = name
        monitor.address = address
        
        
        //3 保存文本框中的值到monitor

//        print(monitor)
        //4
        
        do {
            try managedContext.save()
            
        }catch {
            print("program is error",error)
        }
        
        //5
        monitorName.append(monitor)
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        //从coreData获取数据，只运行一次
                //1
                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
                let managedContext = appDelegate.managedObjectContext
        
                //2
                let fetchRequest = NSFetchRequest(entityName: "MonitorData")
        
        //        //清空数据
        //        monitorName = try! managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
        //        for monitor:NSManagedObject in monitorName {
        //            managedContext.deleteObject(monitor)
        //        }
        //        try! managedContext.save()
        
                //3
                do {
                    
                    monitorName = try managedContext.executeFetchRequest(fetchRequest) as! [MonitorData]
                    
                    //print("show the monitorName",monitorName)
                }
                catch{
                    print(error)
                }
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        return monitorName.count
    }

    
    //每一个cell显示的内容，从monitorName获取
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        
        let monitor = monitorName[indexPath.row]
        cell.textLabel?.text = monitor.name
        // Configure the cell...
        
        return cell
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
//      通过重载来刷新tableview，而不是每次从coredata取
        tableView.reloadData()
        //1
//        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//        
//        let managedContext = appDelegate.managedObjectContext
//        
//        //2
//        let fetchRequest = NSFetchRequest(entityName: "MonitorData")
//        
////        //清空数据
////        monitorName = try! managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
////        for monitor:NSManagedObject in monitorName {
////            managedContext.deleteObject(monitor)
////        }
////        try! managedContext.save()
//        
//        //3
//        do {
//        //monitorName = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
//        
//        }
//        catch{
//            print(error)
//        }
//        
        
    }
    // Override to support conditional editing of the table view. 允许修改cell
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    // Override to support editing the table view. 修改后的操作
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            
//            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//            let managedContext = appDelegate.managedObjectContext
//            let monitor = monitorName[indexPath.row]
//            managedContext.deleteObject(monitor as NSManagedObject)
//            try! managedContext.save()
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDelegate.managedObjectContext
            let monitor = monitorName[indexPath.row]
            
            managedContext.deleteObject(monitor as NSManagedObject)
            try! managedContext.save()
            //先删除数组内的值，在删除值所在cell，否则报错
            monitorName.removeAtIndex(indexPath.row)
            

            
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let address = monitorName[indexPath.row].address! as String
        let alert = UIAlertController(title: "服务器ip", message: "\(address)", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "确定", style: .Default) { (action:UIAlertAction!) -> Void in
            
        }
        alert.addAction(okAction)
        presentViewController(alert, animated: true, completion: nil)
    }
    
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
